<template>
  <div class="hospital-list">
    <!-- 标题和顶部按钮 -->
    <div style="margin-bottom: 15px;">
      <span style="font-size: 25px;font-weight: bold;">医院列表</span>
      <span style="float: right;">
          <el-button type="primary" @click="refreshList">刷新</el-button>
          <el-button type="success" @click="handleAddHospital">新增医院</el-button>
          <el-button 
            type="danger" 
            :disabled="selectedHospitals.length === 0 || deleteLoading" 
            :loading="deleteLoading"
            @click="handleBatchDelete"
          >
            {{ deleteLoading ? '删除中...' : `批量删除 (${selectedHospitals.length})` }}
          </el-button>
      </span>
    </div>
    
    <!-- 搜索区域 -->
    <el-card class="box-card" shadow="hover" style="margin-bottom: 20px;">
      <template #header>
        <div class="card-header">
          <span>搜索条件</span>
        </div>
      </template>
      <div class="search-bar">
        <el-input 
          v-model="searchForm.hospitalName" 
          placeholder="请输入医院名称" 
          style="width: 200px; margin-right: 10px;" 
          clearable
        />
        <el-cascader
          v-model="searchRegionValue"
          :options="regionOptions"
          placeholder="请选择地区"
          style="width: 200px; margin-right: 10px;"
          clearable
          collapse-tags
          collapse-tags-tooltip
          @change="handleSearchRegionChange"
        />
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button type="warning" @click="resetSearch">重置</el-button>
      </div>
    </el-card>
    
    <!-- 数据列表 -->
    <el-card class="box-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div>
            <el-checkbox 
              v-model="selectAll" 
              :indeterminate="isIndeterminate"
              @change="handleSelectAll"
            >
              全选
            </el-checkbox>
            <span style="margin-left: 10px;">医院信息（共{{ pagination.totalCount }}条）</span>
          </div>
        </div>
      </template>
      
      <div v-loading="loading" element-loading-text="正在加载医院数据...">
        <div v-if="hospitalList.length === 0 && !loading" class="empty-state">
          <el-empty description="暂无医院数据" />
        </div>
        
        <div v-else class="hospital-grid">
          <div 
            v-for="hospital in hospitalList" 
            :key="hospital.id" 
            class="hospital-card"
            :class="{ 'selected': selectedHospitalIds.includes(hospital.id) }"
          >
            <div class="card-header">
              <el-checkbox 
                v-model="selectedHospitalIds" 
                :label="hospital.id"
                @change="handleSingleSelect"
              />
              <el-tag v-if="hospital.isRecommended" type="success" size="small">推荐</el-tag>
            </div>
            
            <div class="card-content">
              <div class="hospital-image">
                <img 
                  :src="hospital.image || '/src/assets/医生.png'" 
                  :alt="hospital.hospitalName"
                  @error="handleImageError"
                />
              </div>
              
              <div class="hospital-info">
                <h3 class="hospital-name">{{ hospital.hospitalName }}</h3>
                <div class="hospital-details">
                  <p class="detail-item">
                    <el-icon><Location /></el-icon>
                    <span>{{ hospital.region }} - {{ hospital.detailedAddress }}</span>
                  </p>
                  <p class="detail-item">
                    <el-icon><Phone /></el-icon>
                    <span>{{ hospital.contactInfo }}</span>
                  </p>
                  <p class="detail-item">
                    <el-icon><Star /></el-icon>
                    <span>医院等级：{{ hospital.level }}</span>
                  </p>
                  <p class="detail-item">
                    <el-icon><User /></el-icon>
                    <span>医生数量：{{ hospital.numberOfDoctors }}人</span>
                  </p>
                  <p class="detail-item">
                    <el-icon><Folder /></el-icon>
                    <span>科室数量：{{ hospital.numberOfDepartments }}个</span>
                  </p>
                </div>
                
                <div class="hospital-intro" v-if="hospital.hospitalIntroduction">
                  <div class="intro-text" v-html="hospital.hospitalIntroduction"></div>
                </div>
              </div>
            </div>
            
            <div class="card-actions">
              <el-button size="small" type="primary" @click="viewHospitalDetail(hospital)">
                <el-icon><View /></el-icon>
                查看详情
              </el-button>
              <el-button size="small" type="success" @click="viewDepartments(hospital)">
                <el-icon><Folder /></el-icon>
                科室信息
              </el-button>
              <el-button 
                size="small" 
                type="warning" 
                @click="handleEditHospital(hospital)"
              >
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button 
                size="small" 
                type="danger" 
                :disabled="deleteLoading"
                @click="handleSingleDelete(hospital)"
              >
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 分页 -->
      <el-pagination
        v-if="pagination.totalCount > 0"
        :current-page="pagination.currentPage"
        :page-size="pagination.pageSize"
        :total="pagination.totalCount"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[6, 12, 18, 24]"
        style="margin-top: 20px; text-align: right;"
      />
    </el-card>
    
    <!-- 医院详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="医院详细信息" width="1000px">
      <div v-if="selectedHospital" v-loading="detailLoading">
        <!-- 基本信息 -->
        <el-card class="detail-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>基本信息</span>
            </div>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="医院名称" :span="2">
              <strong>{{ selectedHospital.hospitalName }}</strong>
              <el-tag v-if="selectedHospital.isRecommended" type="success" size="small" style="margin-left: 10px;">推荐医院</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="医院等级">{{ selectedHospital.level }}</el-descriptions-item>
            <el-descriptions-item label="医院类型">{{ selectedHospital.hospitalTypeName || '暂无类型信息' }}</el-descriptions-item>
            <el-descriptions-item label="联系方式">{{ selectedHospital.contactInfo }}</el-descriptions-item>
            <el-descriptions-item label="所在地区">{{ selectedHospital.region }}</el-descriptions-item>
            <el-descriptions-item label="详细地址" :span="2">{{ selectedHospital.detailedAddress }}</el-descriptions-item>
            <el-descriptions-item label="医生数量">{{ selectedHospital.numberOfDoctors }}人</el-descriptions-item>
            <el-descriptions-item label="科室数量">{{ selectedHospital.numberOfDepartments }}个</el-descriptions-item>
            <el-descriptions-item label="医院介绍" :span="2">
              <div v-if="selectedHospital.hospitalIntroduction" v-html="selectedHospital.hospitalIntroduction"></div>
              <span v-else>暂无介绍</span>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 科室设置 -->
        <el-card class="detail-card" shadow="hover" v-if="selectedHospital.departmentSetup && selectedHospital.departmentSetup.length > 0">
          <template #header>
            <div class="card-header">
              <span>科室设置</span>
              <span class="department-count">共 {{ selectedHospital.departmentSetup.length }} 个科室</span>
            </div>
          </template>
          <el-table :data="selectedHospital.departmentSetup" style="width: 100%">
            <el-table-column prop="departmentName" label="科室名称" width="150" />
            <el-table-column prop="type" label="科室类型" width="100" />
            <el-table-column prop="departmentAddr" label="科室地址" :show-overflow-tooltip="true" />
            <el-table-column label="挂号费" width="100">
              <template #default="scope">
                ¥{{ scope.row.registrationFee }}
              </template>
            </el-table-column>
            <el-table-column label="急诊服务" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.isEmergencyService ? 'success' : 'info'">
                  {{ scope.row.isEmergencyService ? '是' : '否' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="在线服务" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.isOnline ? 'success' : 'info'">
                  {{ scope.row.isOnline ? '是' : '否' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" :show-overflow-tooltip="true" />
          </el-table>
        </el-card>

        <!-- 医院图片 -->
        <el-card class="detail-card" shadow="hover" v-if="selectedHospital.image">
          <template #header>
            <div class="card-header">
              <span>医院图片</span>
            </div>
          </template>
          <div class="hospital-image-container">
            <img 
              :src="selectedHospital.image" 
              :alt="selectedHospital.hospitalName"
              class="hospital-detail-image"
              @error="handleImageError"
            />
          </div>
        </el-card>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
    
    <!-- 科室信息对话框 -->
    <el-dialog v-model="departmentDialogVisible" title="科室信息" width="1000px">
      <div v-if="selectedHospital">
        <h4 style="margin-bottom: 16px;">{{ selectedHospital.hospitalName }} - 科室设置</h4>
        <el-table :data="selectedHospital.departmentSetup" style="width: 100%">
          <el-table-column prop="departmentName" label="科室名称" width="150" />
          <el-table-column prop="type" label="科室类型" width="100" />
          <el-table-column prop="departmentAddr" label="科室地址" :show-overflow-tooltip="true" />
          <el-table-column label="挂号费" width="100">
            <template #default="scope">
              ¥{{ scope.row.registrationFee }}
            </template>
          </el-table-column>
          <el-table-column label="急诊服务" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.isEmergencyService ? 'success' : 'info'">
                {{ scope.row.isEmergencyService ? '是' : '否' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="在线服务" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.isOnline ? 'success' : 'info'">
                {{ scope.row.isOnline ? '是' : '否' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" :show-overflow-tooltip="true" />
        </el-table>
      </div>
      <template #footer>
        <el-button @click="departmentDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 新增医院对话框 -->
    <el-dialog 
      v-model="addHospitalDialogVisible" 
      title="新增医院" 
      width="800px" 
      :before-close="handleCloseAddHospitalDialog"
    >
      <el-form
        :model="addHospitalForm"
        :rules="addHospitalRules"
        ref="addHospitalFormRef"
        label-width="120px"
        label-position="left"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="医院名称" prop="hospitalName">
              <el-input 
                v-model="addHospitalForm.hospitalName" 
                placeholder="请输入医院名称"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="医院等级" prop="level">
              <el-select v-model="addHospitalForm.level" placeholder="请选择医院等级" style="width: 100%">
                <el-option label="三级甲等" value="三级甲等" />
                <el-option label="三级乙等" value="三级乙等" />
                <el-option label="三级丙等" value="三级丙等" />
                <el-option label="二级甲等" value="二级甲等" />
                <el-option label="二级乙等" value="二级乙等" />
                <el-option label="一级甲等" value="一级甲等" />
                <el-option label="一级乙等" value="一级乙等" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="医院类型" prop="hospitalTypeId">
              <el-select 
                v-model="addHospitalForm.hospitalTypeId" 
                placeholder="请选择医院类型" 
                style="width: 100%"
                loading-text="加载中..."
              >
                <el-option 
                  v-for="type in hospitalTypes" 
                  :key="type.id" 
                  :label="type.hospitalType" 
                  :value="type.id" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="contactInfo">
              <el-input 
                v-model="addHospitalForm.contactInfo" 
                placeholder="请输入联系电话"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所在地区" prop="regionCodes">
              <el-cascader
                v-model="addHospitalForm.regionCodes"
                :options="regionOptions"
                placeholder="请选择省市区"
                :props="{ 
                  checkStrictly: false, 
                  emitPath: true,
                  value: 'value', 
                  label: 'label', 
                  children: 'children'
                }"
                clearable
                filterable
                style="width: 100%"
                @change="handleRegionChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="医院图片">
              <el-upload
                class="hospital-image-uploader"
                :show-file-list="false"
                :action="'/'"
                :http-request="handleImageUpload"
                :before-upload="beforeImageUpload"
                accept="image/*"
              >
                <div class="upload-area">
                  <img v-if="addHospitalForm.image" :src="addHospitalForm.image" class="uploaded-image" />
                  <div v-else class="upload-placeholder">
                    <el-icon class="upload-icon"><Plus /></el-icon>
                    <div class="upload-text">上传医院图片</div>
                  </div>
                </div>
              </el-upload>
              <el-button 
                v-if="addHospitalForm.image" 
                size="small" 
                type="danger" 
                @click="removeImage"
                style="margin-top: 8px;"
              >
                删除图片
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="详细地址" prop="detailedAddress">
          <el-input 
            v-model="addHospitalForm.detailedAddress" 
            placeholder="请输入详细地址"
            clearable
          />
        </el-form-item>

        <el-form-item label="科室设置" prop="departmentIds">
          <div class="department-transfer-container">
            <el-transfer
              v-model="addHospitalForm.departmentIds"
              :data="departmentTransferData"
              :titles="['可选科室', '已选科室']"
              :button-texts="['', '']"
              :format="{
                noChecked: '${total}',
                hasChecked: '${checked}/${total}'
              }"
              filterable
              filter-placeholder="搜索科室"
            />
          </div>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="医生数量" prop="numberOfDoctors">
              <el-input-number 
                v-model="addHospitalForm.numberOfDoctors" 
                :min="0" 
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="科室数量" prop="numberOfDepartments">
              <el-input-number 
                v-model="addHospitalForm.numberOfDepartments" 
                :min="0" 
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="推荐医院">
              <el-switch v-model="addHospitalForm.isRecommended" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="医院介绍" prop="hospitalIntroduction">
          <div style="border: 1px solid #ccc;">
            <Toolbar
              style="border-bottom: 1px solid #ccc;"
              :editor="addEditorRef"
              :defaultConfig="toolbarConfig"
              mode="default"
            />
            <Editor
              style="height: 200px; overflow-y: hidden;"
              v-model="addHospitalForm.hospitalIntroduction"
              :defaultConfig="editorConfig"
              mode="default"
              @onCreated="handleAddEditorCreated"
            />
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseAddHospitalDialog">取消</el-button>
          <el-button 
            type="primary" 
            @click="handleSubmitAddHospital"
            :loading="addHospitalLoading"
          >
            {{ addHospitalLoading ? '创建中...' : '确定创建' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑医院对话框 -->
    <el-dialog 
      v-model="editHospitalDialogVisible" 
      title="编辑医院信息" 
      width="80%"
      :close-on-click-modal="false"
    >
      <el-form
        ref="editHospitalFormRef"
        :model="editHospitalForm"
        :rules="editHospitalRules"
        label-width="120px"
        style="max-width: 100%"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="医院名称" prop="hospitalName">
              <el-input 
                v-model="editHospitalForm.hospitalName" 
                placeholder="请输入医院名称"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="医院等级" prop="level">
              <el-select 
                v-model="editHospitalForm.level" 
                placeholder="请选择医院等级"
                style="width: 100%"
                clearable
              >
                <el-option label="一级" value="一级" />
                <el-option label="二级" value="二级" />
                <el-option label="三级" value="三级" />
                <el-option label="三级甲等" value="三级甲等" />
                <el-option label="三级乙等" value="三级乙等" />
                <el-option label="三级丙等" value="三级丙等" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="医院类型" prop="hospitalTypeId">
              <el-select 
                v-model="editHospitalForm.hospitalTypeId" 
                placeholder="请选择医院类型"
                style="width: 100%"
                clearable
              >
                <el-option 
                  v-for="type in hospitalTypes" 
                  :key="type.id" 
                  :label="type.hospitalType" 
                  :value="type.id" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="contactInfo">
              <el-input 
                v-model="editHospitalForm.contactInfo" 
                placeholder="请输入联系方式"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="所在地区" prop="region">
          <el-cascader
            v-model="editRegionValue"
            :options="regionOptions"
            placeholder="请选择所在地区"
            style="width: 100%"
            clearable
            @change="handleEditRegionChange"
          />
        </el-form-item>

        <el-form-item label="医院图片">
          <el-upload
            class="hospital-image-uploader"
            :show-file-list="false"
            :action="'/'"
            :http-request="handleEditImageUpload"
            :before-upload="beforeImageUpload"
            accept="image/*"
          >
            <div class="upload-area">
              <img v-if="editHospitalForm.image" :src="editHospitalForm.image" class="uploaded-image" />
              <div v-else class="upload-placeholder">
                <el-icon class="upload-icon"><Plus /></el-icon>
                <div class="upload-text">上传医院图片</div>
              </div>
            </div>
          </el-upload>
          <el-button 
            v-if="editHospitalForm.image" 
            size="small" 
            type="danger" 
            @click="removeEditImage"
            style="margin-top: 8px;"
          >
            删除图片
          </el-button>
        </el-form-item>

        <el-form-item label="详细地址" prop="detailedAddress">
          <el-input 
            v-model="editHospitalForm.detailedAddress" 
            placeholder="请输入详细地址"
            clearable
          />
        </el-form-item>

        <el-form-item label="科室设置" prop="departmentIds">
          <div class="department-transfer-container">
            <el-transfer
              v-model="editHospitalForm.departmentIds"
              :data="departmentTransferData"
              :titles="['可选科室', '已选科室']"
              :button-texts="['', '']"
              :format="{
                noChecked: '${total}',
                hasChecked: '${checked}/${total}'
              }"
              filterable
              filter-placeholder="搜索科室"
            />
          </div>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="医生数量" prop="numberOfDoctors">
              <el-input-number 
                v-model="editHospitalForm.numberOfDoctors" 
                :min="0" 
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="科室数量" prop="numberOfDepartments">
              <el-input-number 
                v-model="editHospitalForm.numberOfDepartments" 
                :min="0" 
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="推荐医院">
              <el-switch v-model="editHospitalForm.isRecommended" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="医院介绍" prop="hospitalIntroduction">
          <div style="border: 1px solid #ccc;">
            <Toolbar
              style="border-bottom: 1px solid #ccc;"
              :editor="editEditorRef"
              :defaultConfig="toolbarConfig"
              mode="default"
            />
            <Editor
              style="height: 200px; overflow-y: hidden;"
              v-model="editHospitalForm.hospitalIntroduction"
              :defaultConfig="editorConfig"
              mode="default"
              @onCreated="handleEditEditorCreated"
            />
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseEditHospitalDialog">取消</el-button>
          <el-button 
            type="primary" 
            @click="handleSubmitEditHospital"
            :loading="editHospitalLoading"
          >
            {{ editHospitalLoading ? '保存中...' : '确定保存' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { searchHospitals, getHospitalTypes, getDepartmentsCascade, getHospitalById } from '@/http/axiosRead'
import { addHospital, uploadFile, deleteHospitals, updateHospital } from '@/http/axiosWrtie'
import type { Hospital, HospitalType, AddHospitalForm, UpdateHospitalForm } from '@/types/hospital'
import regionData from '@/assets/region-options.json'
import { 
  Location, Phone, Star, User, Folder, View, Plus, Delete, Edit 
} from '@element-plus/icons-vue'
import '@wangeditor/editor/dist/css/style.css'
// @ts-ignore
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import type { IDomEditor, IEditorConfig, IToolbarConfig } from '@wangeditor/editor'

// 注册组件
defineOptions({
  components: {
    Editor,
    Toolbar
  }
})

// 响应式数据
const loading = ref(false)
const deleteLoading = ref(false)
const hospitalList = ref<Hospital[]>([])
const selectedHospitalIds = ref<number[]>([])
const selectedHospitals = computed(() => 
  hospitalList.value.filter(hospital => selectedHospitalIds.value.includes(hospital.id))
)

// 搜索表单
const searchForm = reactive({
  hospitalName: '',
  region: ''
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 12,
  totalCount: 0,
  totalPage: 0
})

// 全选相关
const selectAll = ref(false)
const isIndeterminate = computed(() => {
  const selectedCount = selectedHospitalIds.value.length
  return selectedCount > 0 && selectedCount < hospitalList.value.length
})

// 对话框状态
const detailDialogVisible = ref(false)
const departmentDialogVisible = ref(false)
const selectedHospital = ref<Hospital | null>(null)
const detailLoading = ref(false)

// 新增医院相关状态
const addHospitalDialogVisible = ref(false)
const addHospitalLoading = ref(false)
const addHospitalFormRef = ref()

// 选项数据
const hospitalTypes = ref<HospitalType[]>([])
const departmentOptions = ref<any[]>([])
const departmentTransferData = ref<any[]>([])
const regionOptions = ref(regionData as any)

// 新增医院表单
const addHospitalForm = reactive({
  hospitalName: '',
  level: '',
  hospitalTypeId: null as number | null,
  contactInfo: '',
  region: '',
  regionCodes: [] as string[],
  image: '',
  detailedAddress: '',
  departmentIds: [],
  numberOfDoctors: 0,
  numberOfDepartments: 0,
  hospitalIntroduction: '',
  isRecommended: false,
  createPeople: ''
})

// 表单验证规则
const addHospitalRules = reactive({
  hospitalName: [
    { required: true, message: '请输入医院名称', trigger: 'blur' },
    { min: 2, max: 50, message: '医院名称长度在2到50个字符之间', trigger: 'blur' }
  ],
  level: [
    { required: true, message: '请选择医院等级', trigger: 'change' }
  ],
  hospitalTypeId: [
    { required: true, message: '请选择医院类型', trigger: 'change' }
  ],
  contactInfo: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  regionCodes: [
    { required: true, message: '请选择所在地区', trigger: 'change' }
  ],
  detailedAddress: [
    { required: true, message: '请输入详细地址', trigger: 'blur' }
  ],
  departmentIds: [
    { required: true, message: '请选择至少一个科室', trigger: 'change' }
  ],
  numberOfDoctors: [
    { required: true, message: '请输入医生数量', trigger: 'blur' }
  ],
  numberOfDepartments: [
    { required: true, message: '请输入科室数量', trigger: 'blur' }
  ],
  hospitalIntroduction: [
    { required: true, message: '请输入医院介绍', trigger: 'blur' }
  ]
})

// 搜索条件的地区级联选择器
const searchRegionValue = ref<string[]>([])

// 编辑医院相关状态
const editHospitalDialogVisible = ref(false)
const editHospitalLoading = ref(false)
const editHospitalFormRef = ref()

// 编辑医院表单
const editHospitalForm = reactive<UpdateHospitalForm>({
  id: 0,
  hospitalName: '',
  level: '',
  hospitalTypeId: null,
  contactInfo: '',
  region: '',
  image: '',
  detailedAddress: '',
  departmentIds: [],
  numberOfDoctors: 0,
  numberOfDepartments: 0,
  hospitalIntroduction: '',
  isRecommended: false
})

// 编辑医院的地区级联值
const editRegionValue = ref<string[]>([])

// 富文本编辑器实例
const addEditorRef = ref<IDomEditor>()
const editEditorRef = ref<IDomEditor>()

// 富文本编辑器配置
const toolbarConfig: Partial<IToolbarConfig> = {
  // 工具栏配置
  toolbarKeys: [
    'headerSelect',
    'bold',
    'italic',
    'underline',
    'through',
    '|',
    'color',
    'bgColor',
    '|',
    'fontSize',
    'fontFamily',
    '|',
    'indent',
    'delIndent',
    '|',
    'justifyLeft',
    'justifyRight',
    'justifyCenter',
    'justifyJustify',
    '|',
    'insertLink',
    'unLink',
    '|',
    'bulletedList',
    'numberedList',
    '|',
    'insertTable',
    '|',
    'undo',
    'redo',
    '|',
    'fullScreen'
  ]
}

const editorConfig: Partial<IEditorConfig> = {
  // 编辑器配置
  placeholder: '请输入医院介绍...',
  MENU_CONF: {
    fontSize: {
      fontSizeList: ['12px', '14px', '16px', '18px', '20px', '24px', '28px', '32px']
    }
  }
}

// 编辑器创建完毕时的回调函数
const handleAddEditorCreated = (editor: IDomEditor) => {
  addEditorRef.value = editor
}

const handleEditEditorCreated = (editor: IDomEditor) => {
  editEditorRef.value = editor
}

// 编辑医院表单验证规则
const editHospitalRules = reactive({
  hospitalName: [
    { required: true, message: '请输入医院名称', trigger: 'blur' },
    { min: 2, max: 50, message: '医院名称长度在2到50个字符之间', trigger: 'blur' }
  ],
  level: [
    { required: true, message: '请选择医院等级', trigger: 'change' }
  ],
  hospitalTypeId: [
    { required: true, message: '请选择医院类型', trigger: 'change' }
  ],
  contactInfo: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  detailedAddress: [
    { required: true, message: '请输入详细地址', trigger: 'blur' }
  ],
  departmentIds: [
    { required: true, message: '请选择至少一个科室', trigger: 'change' }
  ],
  numberOfDoctors: [
    { required: true, message: '请输入医生数量', trigger: 'blur' }
  ],
  numberOfDepartments: [
    { required: true, message: '请输入科室数量', trigger: 'blur' }
  ],
  hospitalIntroduction: [
    { required: true, message: '请输入医院介绍', trigger: 'blur' }
  ]
})

// 获取医院列表
const fetchHospitals = async () => {
  loading.value = true
  try {
    const params = {
      hospitalName: searchForm.hospitalName || undefined,
      region: searchForm.region || undefined
    }
    
    const res = await searchHospitals(params)
    if (res.data.code === 200) {
      hospitalList.value = res.data.pageData || []
      pagination.totalCount = res.data.totaCount || 0
      pagination.totalPage = res.data.totaPage || 0
      
      ElMessage.success(`成功加载${hospitalList.value.length}条医院数据`)
    } else {
      ElMessage.error(res.data.msg || '获取医院列表失败')
      hospitalList.value = []
    }
  } catch (error) {
    console.error('获取医院列表失败:', error)
    ElMessage.error('网络错误，请稍后重试')
    hospitalList.value = []
  } finally {
    loading.value = false
  }
}

// 搜索功能
const handleSearch = () => {
  pagination.currentPage = 1
  fetchHospitals()
}

// 重置搜索
const resetSearch = () => {
  searchForm.hospitalName = ''
  searchForm.region = ''
  searchRegionValue.value = []
  pagination.currentPage = 1
  fetchHospitals()
}

// 搜索地区级联选择器变化处理
const handleSearchRegionChange = (value: string[]) => {
  if (value && value.length > 0) {
    // 找到选中的地区选项
    const findRegionName = (options: any[], codes: string[], index: number = 0): string => {
      if (index >= codes.length) return ''
      
      const currentOption = options.find(option => option.value === codes[index])
      if (!currentOption) return ''
      
      if (index === codes.length - 1) {
        return currentOption.label
      } else {
        const childName = findRegionName(currentOption.children || [], codes, index + 1)
        return childName ? `${currentOption.label} - ${childName}` : currentOption.label
      }
    }
    
    searchForm.region = findRegionName(regionOptions.value, value)
  } else {
    searchForm.region = ''
  }
}

// 刷新列表
const refreshList = () => {
  fetchHospitals()
}

// 全选处理
const handleSelectAll = (checked: boolean) => {
  if (checked) {
    selectedHospitalIds.value = hospitalList.value.map(hospital => hospital.id)
  } else {
    selectedHospitalIds.value = []
  }
}

// 单选处理
const handleSingleSelect = () => {
  const selectedCount = selectedHospitalIds.value.length
  const totalCount = hospitalList.value.length
  
  if (selectedCount === 0) {
    selectAll.value = false
  } else if (selectedCount === totalCount) {
    selectAll.value = true
  } else {
    selectAll.value = false
  }
}

// 批量删除
const handleBatchDelete = () => {
  ElMessageBox.confirm(
    `您选择了 ${selectedHospitals.value.length} 家医院，确定要删除吗？删除后无法恢复！`,
    '批量删除确认',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    await performDelete(selectedHospitalIds.value)
  }).catch(() => {
    ElMessage.info('已取消删除操作')
  })
}

// 单个删除
const handleSingleDelete = (hospital: Hospital) => {
  ElMessageBox.confirm(
    `确定要删除医院 "${hospital.hospitalName}" 吗？删除后无法恢复！`,
    '删除确认',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    await performDelete([hospital.id])
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 执行删除操作
const performDelete = async (ids: number[]) => {
  deleteLoading.value = true
  try {
    // 获取当前登录用户信息
    const updatePeople = localStorage.getItem('name') || localStorage.getItem('userName') || 'admin'
    
    const response = await deleteHospitals({
      ids: ids,
      updatePeople: updatePeople
    })
    
    if (response.data) {
      const { message, successCount, failCount, failedIds } = response.data
      
      if (failCount === 0) {
        // 全部删除成功
        ElMessage.success(message || `成功删除 ${successCount} 个医院`)
      } else {
        // 部分删除失败，显示详细信息
        ElMessageBox.alert(
          `<div style="text-align: left; line-height: 1.6;">
            <p><strong>删除结果：</strong></p>
            <p>✅ 成功删除：${successCount} 个医院</p>
            <p>❌ 删除失败：${failCount} 个医院</p>
            ${failedIds && failedIds.length > 0 ? `<p><strong>失败的医院ID：</strong>${failedIds.join(', ')}</p>` : ''}
          </div>`,
          '删除结果',
          {
            confirmButtonText: '知道了',
            dangerouslyUseHTMLString: true,
            type: 'warning'
          }
        )
      }
      
      // 清空选中状态
      selectedHospitalIds.value = []
      selectAll.value = false
      
      // 刷新医院列表
      fetchHospitals()
    } else {
      ElMessage.error('删除失败，请重试')
    }
  } catch (error) {
    console.error('删除医院失败:', error)
    ElMessage.error('删除操作失败，请重试')
  } finally {
    deleteLoading.value = false
  }
}

// 分页处理
const handlePageChange = (page: number) => {
  pagination.currentPage = page
  fetchHospitals()
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  fetchHospitals()
}

// 查看医院详情
const viewHospitalDetail = async (hospital: Hospital) => {
  try {
    detailLoading.value = true
    detailDialogVisible.value = true
    
    // 调用API获取医院详细信息
    const response = await getHospitalById(hospital.id)
    
    if (response.data.code === 200) {
      selectedHospital.value = response.data.data
      ElMessage.success('医院信息获取成功')
    } else {
      ElMessage.error(response.data.msg || '获取医院详细信息失败')
      detailDialogVisible.value = false
    }
  } catch (error) {
    console.error('获取医院详细信息失败:', error)
    ElMessage.error('网络错误，请稍后重试')
    detailDialogVisible.value = false
  } finally {
    detailLoading.value = false
  }
}

// 查看科室信息
const viewDepartments = (hospital: Hospital) => {
  selectedHospital.value = hospital
  departmentDialogVisible.value = true
}

// 图片加载错误处理
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  img.src = '/src/assets/医生.png'
}

// 获取医院类型选项
const fetchHospitalTypes = async () => {
  try {
    const res = await getHospitalTypes()
    if (res.data.code === 200) {
      hospitalTypes.value = res.data.data || []
    } else {
      console.error('获取医院类型失败:', res.data.msg)
    }
  } catch (error) {
    console.error('获取医院类型失败:', error)
  }
}

// 获取科室选项
const fetchDepartmentOptions = async () => {
  try {
    const res = await getDepartmentsCascade()
    if (res.data.code === 200) {
      const departments = res.data.data?.departments || []
      
      // 构建穿梭框数据结构
      const buildTransferData = (departments: any[]) => {
        const transferData: any[] = []
        
        // 创建一个ID到科室的映射，方便查找父科室
        const departmentMap = new Map()
        departments.forEach((dept: any) => {
          departmentMap.set(dept.id, dept)
        })
        
        // 递归构建科室路径
        const buildPath = (department: any): string => {
          if (!department || !department.departmentName) {
            return '未知科室'
          }
          
          if (department.parentId === 0 || department.parentId === null || department.parentId === undefined) {
            // 一级科室，直接返回名称
            return department.departmentName
          } else {
            // 子级科室，递归构建路径
            const parent = departmentMap.get(department.parentId)
            if (parent) {
              return `${buildPath(parent)} - ${department.departmentName}`
            } else {
              return department.departmentName
            }
          }
        }
        
        // 为所有科室构建显示名称
        departments.forEach((dept: any) => {
          transferData.push({
            key: dept.id,
            label: buildPath(dept),
            disabled: false
          })
        })
        
        // 按层级和名称排序
        transferData.sort((a: any, b: any) => {
          // 先按层级深度排序（通过 "-" 的数量判断）
          const aLevel = (a.label.match(/-/g) || []).length
          const bLevel = (b.label.match(/-/g) || []).length
          
          if (aLevel !== bLevel) {
            return aLevel - bLevel
          }
          
          // 同级别按名称排序
          return a.label.localeCompare(b.label, 'zh-CN')
        })
        
        return transferData
      }
      
      departmentTransferData.value = buildTransferData(departments)
    } else {
      console.error('获取科室列表失败:', res.data.msg)
    }
  } catch (error) {
    console.error('获取科室列表失败:', error)
  }
}

// 显示新增医院弹窗
const handleAddHospital = async () => {
  // 获取选项数据
  await Promise.all([
    fetchHospitalTypes(),
    fetchDepartmentOptions()
  ])
  
  // 重置表单
  resetAddHospitalForm()
  addHospitalDialogVisible.value = true
}

// 重置新增医院表单
const resetAddHospitalForm = () => {
  Object.assign(addHospitalForm, {
    hospitalName: '',
    level: '',
    hospitalTypeId: null,
    contactInfo: '',
    region: '',
    regionCodes: [],
    image: '',
    detailedAddress: '',
    departmentIds: [],
    numberOfDoctors: 0,
    numberOfDepartments: 0,
    hospitalIntroduction: '',
    isRecommended: false,
    createPeople: ''
  })
  // 清空富文本编辑器内容
  if (addEditorRef.value) {
    addEditorRef.value.clear()
  }
  addHospitalFormRef.value?.clearValidate()
}

// 处理地区变化
const handleRegionChange = (value: string[]) => {
  if (value && value.length > 0) {
    // 获取最后一级的label作为region字段值
    const getRegionLabel = (codes: string[]) => {
      let options = regionOptions.value
      let labels = []
      
      for (const code of codes) {
        const found = options.find((item: any) => item.value === code)
        if (found) {
          labels.push(found.label)
          options = found.children || []
        }
      }
      
      return labels.join(' - ')
    }
    
    addHospitalForm.region = getRegionLabel(value)
  } else {
    addHospitalForm.region = ''
  }
}

// 关闭新增医院弹窗
const handleCloseAddHospitalDialog = () => {
  addHospitalDialogVisible.value = false
  resetAddHospitalForm()
}

// 提交新增医院
const handleSubmitAddHospital = async () => {
  if (!addHospitalFormRef.value) return
  
  try {
    const valid = await addHospitalFormRef.value.validate()
    if (!valid) return
    
    addHospitalLoading.value = true
    
    // 获取当前登录用户信息
    const createPeople = localStorage.getItem('name') || localStorage.getItem('userName') || 'admin'
    
    // 准备提交数据，排除前端辅助字段
    const { regionCodes, ...formData } = addHospitalForm
    const submitData = {
      ...formData,
      hospitalTypeId: addHospitalForm.hospitalTypeId!,  // 确保不是null，因为表单验证已通过
      createPeople: createPeople
    }
    
    const response = await addHospital(submitData)
    
    if (response.data && response.data.id && response.data.id.code === 200) {
      ElMessage.success(response.data.message || '医院创建成功')
      addHospitalDialogVisible.value = false
      resetAddHospitalForm()
      
      // 刷新医院列表
      fetchHospitals()
    } else {
      ElMessage.error(response.data?.id?.msg || '医院创建失败')
    }
  } catch (error) {
    console.error('创建医院失败:', error)
    ElMessage.error('创建医院失败，请重试')
  } finally {
    addHospitalLoading.value = false
  }
}

// 图片上传前验证
const beforeImageUpload = (file: File) => {
  // 检查文件类型
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  
  // 检查文件大小（限制为5MB）
  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过5MB!')
    return false
  }
  
  return true
}

// 处理图片上传
const handleImageUpload = async (option: any) => {
  try {
    console.log('开始上传图片:', option.file.name, option.file.size)
    const response = await uploadFile(option.file)
    console.log('上传响应:', response)
    
    // 根据返回的数据结构调整这里的路径
    let imageUrl = ''
    if (response.data && response.data.url) {
      imageUrl = response.data.url
    } else if (response.data && response.data.data) {
      imageUrl = response.data.data
    } else if (response.data) {
      // 如果直接返回URL字符串
      imageUrl = response.data
    } else {
      // 如果接口返回格式不明确，使用模拟URL（开发环境）
      const timestamp = Date.now()
      imageUrl = `http://101.201.170.32:9000/images/hospital_${timestamp}_${option.file.name}`
    }
    
    console.log('解析后的图片URL:', imageUrl)
    addHospitalForm.image = imageUrl
    ElMessage.success('图片上传成功')
    option.onSuccess(response.data)
  } catch (error: any) {
    console.error('图片上传失败:', error)
    console.error('错误详情:', error.response?.data || error.message)
    ElMessage.error('图片上传失败，请重试')
    option.onError(error)
  }
}

// 删除图片
const removeImage = () => {
  addHospitalForm.image = ''
  ElMessage.success('图片已删除')
}

// 页面加载时获取数据
// 编辑医院相关方法
// 显示编辑医院弹窗
const handleEditHospital = async (hospital: Hospital) => {
  // 获取选项数据
  await Promise.all([
    fetchHospitalTypes(),
    fetchDepartmentOptions()
  ])
  
  // 填充表单数据
  Object.assign(editHospitalForm, {
    id: hospital.id,
    hospitalName: hospital.hospitalName,
    level: hospital.level,
    hospitalTypeId: hospital.hospitalTypeId,
    contactInfo: hospital.contactInfo,
    region: hospital.region,
    image: hospital.image || '',
    detailedAddress: hospital.detailedAddress,
    departmentIds: hospital.departmentSetup ? hospital.departmentSetup.map(dept => dept.id) : [],
    numberOfDoctors: hospital.numberOfDoctors,
    numberOfDepartments: hospital.numberOfDepartments,
    hospitalIntroduction: hospital.hospitalIntroduction || '',
    isRecommended: hospital.isRecommended
  })
  
  // 设置富文本编辑器内容（延迟设置，确保编辑器已创建）
  setTimeout(() => {
    if (editEditorRef.value && hospital.hospitalIntroduction) {
      editEditorRef.value.setHtml(hospital.hospitalIntroduction)
    }
  }, 100)
  
  // 设置地区级联选择器的值
  if (hospital.region) {
    editRegionValue.value = parseRegionToValue(hospital.region)
  } else {
    editRegionValue.value = []
  }
  
  editHospitalDialogVisible.value = true
}

// 解析地区字符串为级联选择器值
const parseRegionToValue = (regionStr: string): string[] => {
  // 这是一个简化的解析函数，实际项目中可能需要更复杂的逻辑
  // 如果有完整的地区映射表，应该使用映射表来解析
  return []
}

// 处理编辑医院的地区变化
const handleEditRegionChange = (value: string[]) => {
  if (value && value.length > 0) {
    const getRegionLabel = (codes: string[]) => {
      let options = regionOptions.value
      let labels = []
      
      for (const code of codes) {
        const found = options.find((item: any) => item.value === code)
        if (found) {
          labels.push(found.label)
          options = found.children || []
        }
      }
      
      return labels.join(' - ')
    }
    
    editHospitalForm.region = getRegionLabel(value)
  } else {
    editHospitalForm.region = ''
  }
}

// 编辑医院的图片上传
const handleEditImageUpload = async (option: any) => {
  try {
    console.log('开始上传图片:', option.file.name, option.file.size)
    const response = await uploadFile(option.file)
    console.log('上传响应:', response)
    
    // 根据返回的数据结构调整这里的路径
    let imageUrl = ''
    if (response.data && response.data.url) {
      imageUrl = response.data.url
    } else if (response.data && response.data.data) {
      imageUrl = response.data.data
    } else if (response.data) {
      // 如果直接返回URL字符串
      imageUrl = response.data
    } else {
      // 如果接口返回格式不明确，使用模拟URL（开发环境）
      const timestamp = Date.now()
      imageUrl = `http://101.201.170.32:9000/images/hospital_edit_${timestamp}_${option.file.name}`
    }
    
    console.log('解析后的图片URL:', imageUrl)
    editHospitalForm.image = imageUrl
    ElMessage.success('图片上传成功')
    option.onSuccess(response.data)
  } catch (error: any) {
    console.error('图片上传失败:', error)
    console.error('错误详情:', error.response?.data || error.message)
    ElMessage.error('图片上传失败，请重试')
    option.onError(error)
  }
}

// 删除编辑医院的图片
const removeEditImage = () => {
  editHospitalForm.image = ''
  ElMessage.success('图片已删除')
}

// 关闭编辑医院弹窗
const handleCloseEditHospitalDialog = () => {
  editHospitalDialogVisible.value = false
  editHospitalFormRef.value?.clearValidate()
}

// 提交编辑医院
const handleSubmitEditHospital = async () => {
  if (!editHospitalFormRef.value) return
  
  try {
    const valid = await editHospitalFormRef.value.validate()
    if (!valid) return
    
    editHospitalLoading.value = true
    
    // 获取当前登录用户信息
    const updatePeople = localStorage.getItem('name') || localStorage.getItem('userName') || 'admin'
    
    // 准备提交数据
    const submitData = {
      ...editHospitalForm,
      hospitalTypeId: editHospitalForm.hospitalTypeId!,  // 确保不是null
      updatePeople: updatePeople
    }
    
    const response = await updateHospital(submitData)
    
    if (response.data) {
      ElMessage.success(response.data.message || '医院信息更新成功')
      editHospitalDialogVisible.value = false
      
      // 刷新医院列表
      fetchHospitals()
    } else {
      ElMessage.error('医院信息更新失败')
    }
  } catch (error: any) {
    console.error('更新医院失败:', error)
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error('更新医院失败，请重试')
    }
  } finally {
    editHospitalLoading.value = false
  }
}

onMounted(() => {
  fetchHospitals()
})

// 组件销毁时，销毁编辑器
onBeforeUnmount(() => {
  if (addEditorRef.value) {
    addEditorRef.value.destroy()
  }
  if (editEditorRef.value) {
    editEditorRef.value.destroy()
  }
})
</script>

<style scoped>
.hospital-list {
  padding: 24px;
  background: #f5f7fa;
}

.search-bar {
  display: flex;
  align-items: center;
  gap: 10px;
}

.box-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header span {
  font-weight: bold;
  font-size: 16px;
}

.empty-state {
  padding: 40px 0;
  text-align: center;
}

.hospital-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
}

.hospital-card {
  border: 1px solid #e4e7ed;
  border-radius: 12px;
  padding: 20px;
  background: white;
  transition: all 0.3s ease;
  position: relative;
}

.hospital-card:hover {
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.hospital-card.selected {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.hospital-card .card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.card-content {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
}

.hospital-image {
  flex-shrink: 0;
  width: 80px;
  height: 80px;
  border-radius: 8px;
  overflow: hidden;
}

.hospital-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.hospital-info {
  flex: 1;
}

.hospital-name {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
  margin: 0 0 12px 0;
}

.hospital-details {
  margin-bottom: 12px;
}

.detail-item {
  display: flex;
  align-items: center;
  margin: 6px 0;
  font-size: 14px;
  color: #606266;
}

.detail-item .el-icon {
  margin-right: 8px;
  color: #909399;
}

.hospital-intro {
  margin-top: 12px;
}

.intro-text {
  font-size: 13px;
  color: #909399;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  margin: 0;
}

.card-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  flex-wrap: wrap;
}

.card-actions .el-button {
  margin: 0;
}

.card-actions .el-button--danger {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

.card-actions .el-button--danger:hover {
  background-color: #f78989;
  border-color: #f78989;
}

/* 新增医院对话框样式 */
.dialog-footer {
  text-align: right;
}

.dialog-footer .el-button {
  margin-left: 10px;
}

/* 表单布局优化 */
.el-form .el-row {
  margin-bottom: 0;
}

.el-form .el-form-item {
  margin-bottom: 18px;
}

/* 图片上传样式 */
.hospital-image-uploader {
  width: 100%;
}

.upload-area {
  width: 200px;
  height: 120px;
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.upload-area:hover {
  border-color: #409eff;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  background: #fafafa;
}

.upload-icon {
  font-size: 28px;
  color: #8c939d;
  margin-bottom: 8px;
}

.upload-text {
  color: #606266;
  font-size: 14px;
}

.uploaded-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

/* 科室穿梭框样式 */
.department-transfer-container {
  width: 100%;
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

:deep(.el-transfer) {
  display: flex;
  align-items: flex-start;
}

:deep(.el-transfer-panel) {
  width: 250px;
  height: 300px;
}

:deep(.el-transfer-panel__header) {
  background: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  font-weight: 500;
}

:deep(.el-transfer-panel__body) {
  height: 246px;
}

:deep(.el-transfer-panel__list) {
  height: 216px;
  overflow-y: auto;
}

:deep(.el-transfer-panel__item) {
  padding: 8px 15px;
  line-height: 20px;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.el-transfer-panel__item:hover) {
  background: #f5f7fa;
}

/* 科室层级样式 */
:deep(.el-transfer-panel__item .el-checkbox__label) {
  font-size: 13px;
  color: #606266;
  word-break: break-all;
  line-height: 18px;
  display: block;
  white-space: normal;
}

:deep(.el-transfer__buttons) {
  padding: 0 20px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

:deep(.el-transfer__button) {
  margin: 5px 0;
  padding: 8px 12px;
  border-radius: 4px;
}

/* 医院详情对话框样式 */
.detail-card {
  margin-bottom: 20px;
}

.detail-card .card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.department-count {
  font-size: 14px;
  color: #909399;
}

.hospital-image-container {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

.hospital-detail-image {
  max-width: 100%;
  max-height: 400px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 富文本编辑器样式 */
:deep(.w-e-text-container) {
  font-size: 14px;
  line-height: 1.6;
}

:deep(.w-e-toolbar) {
  border-bottom: 1px solid #dcdfe6;
  background-color: #f5f7fa;
}

:deep(.w-e-text-container p) {
  margin: 10px 0;
}

:deep(.w-e-text-container ul, .w-e-text-container ol) {
  margin: 10px 0;
  padding-left: 20px;
}

:deep(.w-e-text-container blockquote) {
  margin: 10px 0;
  padding-left: 10px;
  border-left: 3px solid #409eff;
  background-color: #f5f7fa;
}

:deep(.w-e-text-container table) {
  border-collapse: collapse;
  width: 100%;
  margin: 10px 0;
}

:deep(.w-e-text-container table td, .w-e-text-container table th) {
  border: 1px solid #dcdfe6;
  padding: 8px;
  text-align: left;
}

:deep(.w-e-text-container table th) {
  background-color: #f5f7fa;
  font-weight: bold;
}

/* 医院简介显示优化 */
.hospital-intro .intro-text {
  /* 如果医院简介包含HTML，需要处理样式 */
  line-height: 1.5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .hospital-grid {
    grid-template-columns: 1fr;
  }
  
  .card-content {
    flex-direction: column;
  }
  
  .hospital-image {
    width: 100%;
    height: 120px;
  }
  
  .hospital-detail-image {
    max-height: 300px;
  }
  
  /* 富文本编辑器移动端优化 */
  :deep(.w-e-toolbar) {
    flex-wrap: wrap;
  }
  
  :deep(.w-e-text-container) {
    min-height: 150px !important;
  }
}
</style>